package work.mediway.mdm.biz.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mediway.hos.messgateway.model.entity.MessageEntity;
import com.mediway.hos.messgateway.model.entity.MessageType;
import com.mediway.hos.messgateway.service.MessageTypeService;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.core.helper.BaseDatabaseHelper;
import work.mediway.mdm.core.constant.MdmConstant;
import work.mediway.mdm.core.exception.DataException;
import work.mediway.mdm.core.vo.TableVO;
import work.mediway.mdm.biz.dto.dict.DictFieldDTO;
import work.mediway.mdm.biz.event.DataPushEventEventPublisher;
import work.mediway.mdm.biz.service.common.CommonDictService;

/**
 * 测试任务
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2022/6/22
 */
@Slf4j
@Component("testJob")
@RequiredArgsConstructor
public class TestJob {

    private final DataPushEventEventPublisher dataPushEventEventPublisher;
    private final MessageTypeService messageTypeService;
    private final BaseDatabaseHelper baseDatabaseHelper;
    private final SqlSessionTemplate sqlSessionTemplate;
    private final CommonDictService commonDictService;

    public void testDataPush(String tableCode) {
        Assert.notBlank(tableCode);
        List<TableVO> table = baseDatabaseHelper.getTable(tableCode);
        if (CollUtil.isEmpty(table)) {
            throw new DataException(StrUtil.format("tableCode = {} 不存在", tableCode));
        }
        // 查询需要转发数据
        Page<Map<String, Object>> page = commonDictService.dictDetailShowOrExportAll(DictFieldDTO.getInstance().setTableCode(tableCode));
        MessageType messageType = new MessageType();
        messageType.setTypeName(table.get(0).getTableCode());
        List<MessageType> messageTypes = messageTypeService.selectAllMessageTypeList(messageType);
        if (CollUtil.isEmpty(messageTypes)) {
            log.info("字典表tableCode = {} 未绑定任何消息", tableCode);
            return;
        }
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setTypeId(messageTypes.get(0).getTypeId());
        messageEntity.setEntityBody(StrUtil.format(MdmConstant.DICT_GENERAL_STYLE, JSONUtil.toJsonStr(page.getRecords()), tableCode));
        dataPushEventEventPublisher.publishEvent(messageEntity);
    }

}
